package sessions

import (
	"fmt"
	"github.com/gorilla/sessions"
	"net/http"
)

var store = sessions.NewCookieStore([]byte("something-very-secret"))

func init() {
	http.HandleFunc("/save", SaveSession)
	http.HandleFunc("/get", GetSession)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Http Server failed!")
		return
	}
}

func GetSession(writer http.ResponseWriter, request *http.Request) {
	session, err := store.Get(request, "session-name")
	if err != nil {
		http.Error(writer, err.Error(), http.StatusInternalServerError)
		return
	}
	foo := session.Values["foo"]
	num := session.Values[42]
	fmt.Println(foo, num)
}

func SaveSession(writer http.ResponseWriter, request *http.Request) {
	session, err := store.Get(request, "session-name")
	if err != nil {
		http.Error(writer, err.Error(), http.StatusInternalServerError)
	}

	session.Values["foo"] = "bar"
	session.Values[42] = 43
	// 将session的最大存储时间设置为小于零的数即为删除
	//session.Options.MaxAge = -1

	sessions.Save(request, writer)
}
